package com.example.blogsystem.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Slf4j
public class UploadFileUtils {
    public static String uploadFile(MultipartFile file){
        if(file == null || file.isEmpty()){
            return "";
        }
        String fileName = file.getOriginalFilename();
        String finalName = UUID.randomUUID() + "_" + fileName;

        try {
            //获取上传文件的路径
            List<File> uploadPath = getUploadPath();
            File targetFile = new File(uploadPath.get(0), finalName);
            file.transferTo(targetFile);
            FileCopyUtils.copy(targetFile, new File(uploadPath.get(1), finalName));
            log.info("上传classPath: " + uploadPath.get(0));
            log.info("resourcePath: " + uploadPath.get(1));
            log.info("classPath: " + ResourceUtils.getURL("classpath:"));

        } catch (IOException e) {
            log.error("获取文件路径失败: e{}", e);
        }

        return finalName;
    }

    public static List<File> getUploadPath() throws FileNotFoundException {
        //1、类目录
        File classPath = new File(ResourceUtils.getURL("classpath:").getPath());
        if(!classPath.exists()){
            classPath = new File("/");
        }

        File classFile = new File(classPath.getPath(), "head");

        //2、工作目录
        File resourceFile = new File( "./src/main/resources/static/pic/head");

        //3、判断是否存在，如果不存在就创建
        if(!classFile.exists()){
            classFile.mkdirs();
        }
        if(!resourceFile.exists()){
            resourceFile.mkdirs();
        }

        return Arrays.asList(classFile, resourceFile);
    }
}
